import { openDB } from 'idb';
import { getValueBykey, saveValue, getLoginUserId } from "./dbKV"

// 打开或创建历史记录数据库
const dbPromise = openDB('history-db', 1, {
    upgrade(db) {
        const store = db.createObjectStore('history', { keyPath: 'id', autoIncrement: true });
        // 声明表的索引，可用此索引作检索where
        store.createIndex("message", "message", { unique: false });
    }
})

// 添加历史记录
export async function addHistoryData(historyObject) {
    const db = await dbPromise;
    delete historyObject.id;
    db.add('history', historyObject)
    console.log("收到消息，存入indexDB", historyObject);
}

// 批量添加历史记录（获取私人聊天记录）
export async function batchAddHistory(historysList) {
    const db = await dbPromise;
    for (let hisItem of historysList) {
        delete hisItem.id;
        db.add('history', hisItem)
    }
    console.log(historysList);
    console.log("批量添加/同步数据完成,共同步数据量：", historysList.length);
}

// 传入接收者ID找出所有IndexDB中聊天记录
export async function getAllChatRecord(receiverId) {
    // 取出当前登录用户ID
    const userInfo = await getValueBykey("userInfo");
    let loginId = userInfo.userId;

    console.log("获取聊天记录-当前登录ID");

    // 打开数据库并开始事务
    const db = await dbPromise;
    const tx = db.transaction('history', 'readonly');
    const store = tx.objectStore('history');

    // 获取所有记录
    const records = await store.getAll();

    // 过滤符合条件的聊天记录
    const filteredRecords = records.filter(
        record =>
            (record.receiver === receiverId && record.sender === loginId) ||
            (record.sender === receiverId && record.receiver === loginId)
    );

    // 返回过滤后的聊天记录
    return filteredRecords;
}

// 查询群组的聊天记录
export async function getGroupChatRecord(receiverId) {
    // 打开数据库并开始事务
    const db = await dbPromise;
    const tx = db.transaction('history', 'readonly');
    const store = tx.objectStore('history');

    // 获取所有记录
    const records = await store.getAll();

    // 过滤符合条件的聊天记录
    const filteredRecords = records.filter(
        record =>
            (record.receiver == receiverId)
    );

    // 返回过滤后的聊天记录
    return filteredRecords;
}

// 分拣出聊天记录对象列表
export async function getChatObjectList() {
    // 打开已创建的 IndexedDB 数据库
    const db = await openDB('history-db', 1);

    // 获取当前登录用户ID，用于聊天列表去重
    let userId = await getLoginUserId();

    // 访问存储的数据
    const tx = db.transaction('history', 'readonly');
    const store = tx.objectStore('history');

    // 创建一个 Set 用于存储去重的 receiver
    const receiverSet = new Set();

    // 使用游标遍历所有记录
    let cursor = await store.openCursor();
    while (cursor) {
        if (cursor.value.receiver != userId && cursor.value.msgType != "person") { // 取群组接收者
            // 将每个记录的 receiver 加入 Set
            receiverSet.add(cursor.value.receiver);
        }

        // 构造私发的聊天列表
        if (cursor.value.msgType == "person" && cursor.value.sender != userId) { 
            receiverSet.add(cursor.value.sender);
        }

        if (cursor.value.msgType == "person" && cursor.value.receiver != userId) { 
            receiverSet.add(cursor.value.receiver);
        }

        cursor = await cursor.continue();
    }

    // 将所有接收者ID存入indexDB中
    saveValue("chat-ids", receiverSet)
}


// 根据消息内容查询历史记录
export async function getHistoryByContent(content) {
    const db = await dbPromise;
    const index = db.transaction('history').store.index("message");
    // 模糊搜索
    const result = await index.get(content)
    // TODO 取出检索后的数据，将历史记录中的用户id或群组id查询出名称

}

// 获取聊天对象的最后一条记录
export async function getEndMassageByreceiverId(receiverId) {
    // 打开数据库
    const db = await dbPromise;
    const tx = db.transaction('history', 'readonly');
    const store = tx.objectStore('history');

    // 创建游标，用于遍历所有记录
    let cursor = await store.openCursor();
    let lastMessage = null;

    while (cursor) {
        const record = cursor.value;

        // 检查 receiver 是否匹配
        if (record.receiver === receiverId) {
            // 如果是匹配的，更新 lastMessage 为时间戳最新的记录
            if (!lastMessage || record.timestamp > lastMessage.timestamp) {
                lastMessage = record;
            }
        }
        cursor = await cursor.continue();
    }

    await tx.done;
    return lastMessage;
}

// 获取私聊类型的最后一条历史记录
export async function getEndMessagePrivate(receiverId) {

    // 获取当前登录用户ID
    let userInfo = await getValueBykey("userInfo");
    let userId = userInfo.userId;

    // 打开数据库
    const db = await dbPromise;
    const tx = db.transaction('history', 'readonly');
    const store = tx.objectStore('history');

    // 创建游标，用于遍历所有记录
    let cursor = await store.openCursor();
    console.log("opened");
    let lastMessage = null;

    while (cursor) {
        const record = cursor.value;

        // 过滤出聊天双方的最后一条聊天记录
        if (record.receiver == receiverId && record.sender == userId ||
            record.receiver == userId && record.sender == receiverId
        ) {
            if (!lastMessage || record.timestamp > lastMessage.timestamp) {
                lastMessage = record;
            }
        }
        cursor = await cursor.continue();
    }

    await tx.done;
    return lastMessage;

}

// 获取最后一条数据的方法
export async function getLastRecord() {
    // 打开数据库
    const db = await dbPromise;

    // 通过事务和对象存储获取数据
    const tx = db.transaction('history', 'readonly');
    const store = tx.objectStore('history');

    // 使用游标按主键id倒序排序并只获取第一条
    const cursor = await store.openCursor(null, 'prev');

    // 获取到第一条记录，即最后插入的数据
    const lastRecord = cursor ? cursor.value : null;

    // 关闭事务
    await tx.done;

    return lastRecord;
}




